package com.henry.jvm;

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class ConstantPoolTest {
    @Test
    public void fun1() {
        String s = new String("1");
        System.out.println("s:"+System.identityHashCode(s));
        String s1=s.intern();
        System.out.println("s1:"+System.identityHashCode(s1));
        String s2 = "1";
        System.out.println("s2:"+System.identityHashCode(s2));
        System.out.println(s == s2);
        System.out.println(s1 == s2);

        String s3 = new String("1") + new String("1");
        System.out.println("s3:"+System.identityHashCode(s3));
        String s4=s3.intern();
        System.out.println("s4:"+System.identityHashCode(s4));
        String s5 = "11";
        System.out.println("s5:"+System.identityHashCode(s5));
        System.out.println(s3 == s4);
        System.out.println(s5 == s4);
    }

    @Test
    public void fun2() {
        StringBuilder sb = new StringBuilder();
        List<String> list = new ArrayList<>();
        int len =1024;
        for (int i = 65;i<91 ; i++) {
            System.out.println(list.size());
            for (int j = 0; j < len; j++) {
                sb.append((char)i);
            }
            String s = sb.toString();
            //s.intern()执行不执行,出现java heap space oom时,list的size一样  说明intern()方法并没有在常量池中新增一个字符串 ,而仅仅是在常量池中保存一个指向堆内存的引用
            //测试环境jdk版本:1.8
//            s.intern();
            list.add(s);
            sb = new StringBuilder();
            if(i==90){
                len=len*2;
                i=64;
            }
        }
//        System.out.println((byte)'a');
//        System.out.println((byte)'z');
//        System.out.println((byte)'A');
//        System.out.println((byte)'Z');

    }
}
